package com.framework.core.utils;

import android.text.TextUtils;

import org.apache.commons.codec.binary.Hex;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author shenmengchao
 * @version 1.0.0
 * @date 2017/8/11
 * @description
 */

public class SignUtil {

    public final static String SECRET = "4FTxLuDSQBK5UdU5SwIb";

    public static boolean isMapEmpty(HashMap<String, Object> param) {
        if (null == param || param.size() == 0) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) throws Exception {
        HashMap<String, Object> param = new HashMap<>();
        param.put("accessAction", "getAccountsByStbId");
        param.put("accessKey", "key_admin");
        param.put("stbId", "testStbId");
        param.put("timestamp", "1534215231785");
        String sign = generateSignature(param, "secret_admin");
        System.out.println("sign = " + sign);
    }

    public static String generateSignature(HashMap<String, Object> param, String secret) throws Exception {

        if (isEmpty(secret) || isMapEmpty(param)) {
            return null;
        }
        List<String> keyList = new ArrayList<String>(param.keySet());
        Collections.sort(keyList, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder(secret);
        for (String key : keyList) {
            if (param.get(key) != null) {

                if (!key.equals("signature")) {
                    sb.append(key);
                    sb.append("=");
                    sb.append(param.get(key));
                }
            }
        }
        System.out.println();
        String signature = hmacSHA256Encrypt(sb.toString(), secret);
        return signature;
    }

    public static boolean isEmpty(CharSequence str) {
        return str == null || str.length() == 0;
    }

    /**
     * 使用 HMAC-SHA256 签名方法对对plainText进行签名
     *
     * @param plainText    被签名的字符串
     * @param accessSecret 密钥
     * @return
     * @throws Exception
     */
    public static String hmacSHA256Encrypt(String plainText, String accessSecret) throws Exception {

        Mac mac = Mac.getInstance("HmacSHA256");
        byte[] secretByte = accessSecret.getBytes("UTF-8");
        byte[] dataBytes = plainText.getBytes("UTF-8");
        SecretKey secret = new SecretKeySpec(secretByte, "HMACSHA256");

        mac.init(secret);
        byte[] doFinal = mac.doFinal(dataBytes);
        byte[] hexB = new Hex().encode(doFinal);
        String signature = new String(hexB);
        return signature;
    }
}
